﻿Imports System.ComponentModel
Imports ATS.UI.Process
Imports ATS.Business.Entities
Imports System.Globalization
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Channels
Imports System.Collections.Specialized


Public Class UserAdministration
    Private WithEvents _backgroundWorker As BackgroundWorker
    Private WithEvents _backgroundWorker_Save As BackgroundWorker
    Private WithEvents _backgroundWorker_Delete As BackgroundWorker
    Private WithEvents _backgroundWorker_CheckUser As BackgroundWorker
    Public WithEvents oWindowList As OpenedWindowList = OpenedWindowList.GetList()
    Private WithEvents oWindow As OpenedWindowClass
    Private _upc As SubmitterUserProcess = Nothing
    'Private _userList As List(Of UserTable) = Nothing
    Public WithEvents _userList As IObserveUserTable
    Private _userDetail As UserTable = Nothing
    Private _userDetail_asynch As UserTable = Nothing
    Dim key As String = "ATSbyJOKOforGENCPROSv2.1"

#Region "Window Events"

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        _upc = New SubmitterUserProcess()
    End Sub

    Private Sub UserAdministration_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        Dim ied As IEnumerable(Of OpenedWindowClass) = From d In oWindowList Where d.WindowID = Me.Name
        oWindowList.Remove(ied.First)
        If Application.Current.Windows.Count = 1 Then
            Application.Current.Windows(0).Activate()
        End If
    End Sub

    Private Sub UserAdministration_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        If Not _userDetail Is Nothing Then
            If _userDetail.IsDirty Then
                If _
                    MessageBox.Show("There are unsaved entries. Do you really want to exit?", "Exit", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.No Then
                    e.Cancel = True
                End If
            End If
        End If
    End Sub

    Private Sub UserAdministration_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
    End Sub




#End Region

#Region "Support Procedures"

    Private Sub RefreshRecordCount()
        If Not _userList Is Nothing Then
            If _userList.Count = 1 Then
                ExpanderText.Text = _userList.Count & " record found"
            Else
                ExpanderText.Text = _userList.Count & " records found"
            End If
        End If
    End Sub

    Private Sub LoadUsers()
        ' _userList = _upc.GetAllUsers.ToList '.OrderBy(Function(x) x.Username)

        Try
            If IObserveUserTable.list.Count = 0 Then
                For Each item In _upc.GetAllUsers.OrderBy(Function(x) x.Username)
                    With item
                        IObserveUserTable.list.Add(New UserTable(.Unique_Key _
                                                                   , .Username _
                                                                   , .Hashed _
                                                                   , .Salt _
                                                                   , .LastPasswordChangeDateTime _
                                                                   , .AccountLocked _
                                                                   , .LockedDateTime _
                                                                   , .NumberOfPasswordTry _
                                                                   , .LastLogin _
                                                                   , .ChangePassword))
                    End With
                Next
                '_userList = _upc.IObservableListGetAllUsers
            End If
            _userList = IObserveUserTable.list
        Catch ex As Exception
            MessageBox.Show(ex.Message & ControlChars.Lf & ex.ToString, "Error loading user list", MessageBoxButton.OK, _
                             MessageBoxImage.[Error])
        End Try


        '_userList = _upc.IObservableListGetAllUsers
        'Me.DataContext = _userList
    End Sub

    Sub sortData()
        Dim ied As IEnumerable(Of UserTable) = From d In _userList Order By d.Username
        For Each i In ied
            _userList.Remove(i)
            _userList.Add(i)
        Next
    End Sub

    Private Sub Data_CollectionChanged( _
                                        ByVal sender As Object, _
                                        ByVal e As NotifyCollectionChangedEventArgs) _
        Handles _userList.CollectionChanged

        ' Did you add or remove an item in the collection?
        If e.Action = NotifyCollectionChangedAction.Add Or _
           e.Action = NotifyCollectionChangedAction.Remove Then
            RefreshRecordCount()
        End If
    End Sub

    Private Sub LoadSelectedUserDetails()
        If listBoxUsers.SelectedIndex >= 0 Then
            _userDetail = listBoxUsers.SelectedItem
            passwordboxPassword.Password = "PASSWORD"
            _userDetail.ResetDirtyBit()
            HookupChangeEventHandler(_userDetail)
            mainOverlay.Visibility = Visibility.Collapsed
            Me.Title = textboxUser.Text
        Else
            _userDetail = Nothing
            Me.Title = "User Administration"
            mainOverlay.Visibility = Visibility.Visible
        End If
        If Not _userDetail Is Nothing Then
            SetWindowProperties(_userDetail.IsDirty)
        Else
            SetWindowProperties(False)
        End If

    End Sub

    Private Sub HookupChangeEventHandler(userDetail As UserTable)
        ' Add a PropertyChanged event handler for 
        ' the specified Customer instance:
        AddHandler userDetail.PropertyChanged, _
            AddressOf HandlePropertyChanged
    End Sub

    Private Sub HandlePropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
        If _userDetail.IsDirty Then
            SetWindowProperties(_userDetail.IsDirty)
        End If
    End Sub

    Public Function FilterUserTable(ByVal t As Object) As Boolean
        Dim _users As UserTable
        _users = t
        Return _users.Username.ToUpper.Contains(searchBox.Text.ToUpper)
    End Function

    Private Sub SetWindowProperties(dirty As Boolean)
        If dirty Then
            Me.Title &= If(Not Me.Title.ToUpper.Contains("UNSAVED"), " (unsaved)", "")
        Else
            Me.Title = If(Title.ToUpper.Contains("UNSAVED"), Me.Title.Substring(0, Me.Title.Length - 10), Me.Title)
        End If

        For itemIndex = 0 To oWindowList.Count - 1
            If oWindowList(itemIndex).WindowID = Me.Name Then
                oWindowList(itemIndex).WindowName = Me.Title
                oWindowList(itemIndex).WindowIsDirty = dirty
            End If
        Next
    End Sub

    Sub SaveUserDetails()
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Visible
        Try
            Dim tripleDESNP = New tripleDes
            tripleDESNP.secretKey = key
            tripleDESNP.data = passwordboxPassword.Password
            If tripleDESNP.encryptdata() Then
                _userDetail.Hashed = tripleDESNP.encryptedData()
            Else
                Throw New Exception("Could not encrypt password.")
            End If
            _userDetail.AccountLocked = cbLocked.IsChecked

            _backgroundWorker_Save = New BackgroundWorker
            If _userList.Where(Function(x) x.Username = textboxUser.Text).Count > 0 Then
                'edit
                _backgroundWorker_Save.RunWorkerAsync("edit")
            Else
                'new
                _backgroundWorker_Save.RunWorkerAsync("new")

                'update list
                _userList.Add(_userDetail)
                sortData()
                Dim ctr As Integer = 0
                For Each item In _userList
                    If item.Unique_Key = _userDetail.Unique_Key Then
                        Exit For
                    End If
                    ctr += 1
                Next
                listBoxUsers.SelectedIndex = ctr
            End If
            SetWindowProperties(_userDetail.IsDirty)
            _backgroundWorker_Save.Dispose()


        Catch faultEx As FaultException
            MessageBox.Show(faultEx.Message, "Error Saving User Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error Saving User Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        End Try

    End Sub

    Sub DeleteUser()
        Try
            If Not _userDetail Is Nothing Then
                _backgroundWorker_Delete = New BackgroundWorker
                _backgroundWorker_Delete.RunWorkerAsync()
                _backgroundWorker_Delete.Dispose()
                _userList.Remove(_userDetail)
            End If
        Catch faultEx As FaultException
            MessageBox.Show(faultEx.Message, "Error Deleting User Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error Deleting User Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        End Try

    End Sub

#End Region

#Region "Control Events"

    Private Sub ExpanderList_Expanded(sender As Object, e As RoutedEventArgs) Handles ExpanderList.Expanded
        _backgroundWorker = New BackgroundWorker
        _backgroundWorker.RunWorkerAsync()
    End Sub

    Private Sub buttonSave_Click(sender As Object, e As RoutedEventArgs) Handles buttonSave.Click
        If Not _userDetail Is Nothing Then
            If _userDetail.IsDirty And EntryValidation.ValidatePassword(passwordboxPassword) Then
                SaveUserDetails()
            End If
        End If
    End Sub


    Private Sub buttonNew_Click(sender As Object, e As RoutedEventArgs) Handles buttonNew.Click
        'ExpanderList.IsExpanded = True
        If Not _userDetail Is Nothing Then
            If _userDetail.IsDirty Then
                If _
                    MessageBox.Show("There are unsaved entries. Do you want to abandon your changes?", "Refresh", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    passwordboxPassword.Password = "PASSWORD"
                    _userDetail.ResetDirtyBit()
                    SetWindowProperties(_userDetail.IsDirty)
                    MyCanvas.Visibility = Windows.Visibility.Visible
                End If
            Else
                MyCanvas.Visibility = Windows.Visibility.Visible
            End If
        Else
            MyCanvas.Visibility = Windows.Visibility.Visible
        End If
    End Sub

    Private Sub passwordboxPassword_GotFocus(sender As Object, e As RoutedEventArgs) _
        Handles passwordboxPassword.GotFocus
        EntryValidation.ValidatePassword(passwordboxPassword)
        passwordboxPassword.Password = Nothing
    End Sub

    Private Sub passwordboxPassword_LostFocus(sender As Object, e As RoutedEventArgs) _
        Handles passwordboxPassword.LostFocus
        EntryValidation.ValidatePassword(passwordboxPassword)
    End Sub

    Private Sub passwordboxPassword_PasswordChanged(sender As Object, e As RoutedEventArgs) _
        Handles passwordboxPassword.PasswordChanged
        EntryValidation.ValidatePassword(passwordboxPassword)
        If Not textboxUser.Text.Length = 0 Then
            With _userDetail
                .Hashed = passwordboxPassword.Password
            End With
            SetWindowProperties(_userDetail.IsDirty)
        End If

    End Sub

    Private Sub listBoxUsers_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) _
        Handles listBoxUsers.SelectionChanged
        If Not _userDetail Is Nothing Then
            If _userDetail.IsDirty Then
                If _
                    MessageBox.Show("Save entries before leaving?", "Save Data", MessageBoxButton.YesNo, _
                                     MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    SaveUserDetails()
                End If
            End If
        End If
        LoadSelectedUserDetails()
    End Sub

    Private Sub searchBox_GotFocus(sender As Object, e As RoutedEventArgs) Handles searchBox.GotFocus
        If searchBox.Text.ToUpper.Contains("SEARCH") Then
            searchBox.Text = Nothing
        End If
    End Sub

    Private Sub searchBox_TextChanged(sender As Object, e As TextChangedEventArgs) Handles searchBox.TextChanged
        If Not listBoxUsers Is Nothing Then
            Dim icview As ICollectionView = CollectionViewSource.GetDefaultView(Me.DataContext)
            icview.Filter = New Predicate(Of Object)(AddressOf FilterUserTable)
        End If
    End Sub

    Private Sub buttonRefresh_Click(sender As Object, e As RoutedEventArgs) Handles buttonRefresh.Click
        If Not _userDetail Is Nothing Then
            If _userDetail.IsDirty Then
                If MessageBox.Show("There are unsaved entries. Do you really want to refresh the data?", "Refresh", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    LoadSelectedUserDetails()
                End If
            End If
        End If
    End Sub

    Private Sub buttonDelete_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonDelete.Click
        DeleteUser()
    End Sub

#End Region

#Region "Background Workers"
    Private Sub _backgroundWorker_ChckUserDoWork( _
                                          ByVal sender As Object, _
                                          ByVal e As DoWorkEventArgs) _
        Handles _backgroundWorker_CheckUser.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        e.Result = _upc.UserExists(e.Argument)

    End Sub

    Private Sub _backgroundWorker_ChckUserRunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker_CheckUser.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            If e.Result Then
                UcNewUser.LabelError.Content = "Username already exist."
            Else
                listBoxUsers.SelectedIndex = -1
                _userDetail = New UserTable()
                _userDetail.Username = UcNewUser.TextBoxNewUser.Text
                _userDetail.AccountLocked = False
                textboxUser.Text = UcNewUser.TextBoxNewUser.Text
                passwordboxPassword.Password = Nothing
                cbLocked.IsChecked = False
                MyCanvas.Visibility = Windows.Visibility.Collapsed
                mainOverlay.Visibility = Visibility.Collapsed
                Me.Title = _userDetail.Username
                SetWindowProperties(_userDetail.IsDirty)
            End If
        End If
        UcNewUser.busyAnimationNewUser_visibility = Windows.Visibility.Collapsed
    End Sub
    Private Sub _backgroundWorker_SaveDoWork( _
                                          ByVal sender As Object, _
                                          ByVal e As DoWorkEventArgs) _
        Handles _backgroundWorker_Save.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        If e.Argument = "edit" Then
            _userDetail_asynch = _upc.UpdateUSer(_userDetail)
        ElseIf e.Argument = "new" Then
            _userDetail_asynch = _upc.CreateNewUSer(_userDetail)
        End If
    End Sub

    Private Sub _backgroundWorker_SaveRunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker_Save.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            Me.DataContext = _userList
            busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
            _userDetail = _userDetail_asynch
            _userDetail_asynch = Nothing
            _userDetail.ResetDirtyBit()
        End If
    End Sub

    Private Sub _backgroundWorker_DeleteDoWork( _
                                          ByVal sender As Object, _
                                          ByVal e As DoWorkEventArgs) _
        Handles _backgroundWorker_Delete.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        _upc.DeleteUser(_userDetail)
    End Sub

    Private Sub _backgroundWorker_DeleteRunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker_Delete.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    ' This event handler is where the actual work is done.
    Private Sub _backgroundWorker_DoWork( _
                                          ByVal sender As Object, _
                                          ByVal e As DoWorkEventArgs) _
        Handles _backgroundWorker.DoWork
        ' Get the BackgroundWorker object that raised this event.
        Dim worker As BackgroundWorker = _
                CType(sender, BackgroundWorker)
        ' Assign the result of the computation
        ' to the Result property of the DoWorkEventArgs
        ' object. This is will be available to the 
        ' RunWorkerCompleted eventhandler.
        LoadUsers()
    End Sub

    'backgroundWorker1_DoWork

    Private Sub _backgroundWorker_RunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker.RunWorkerCompleted

        ' First, handle the case where an exception was thrown.
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            Me.DataContext = _userList
            RefreshRecordCount()
            If _userDetail Is Nothing Then
                listBoxUsers.SelectedIndex = -1
            End If
            busyAnimation.Visibility = Windows.Visibility.Collapsed

        End If
    End Sub

    'backgroundWorker1_RunWorkerCompleted

    '' This event handler updates the progress bar.
    'Private Sub _backgroundWorker_ProgressChanged( _
    '                                               ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
    '    Handles _backgroundWorker.ProgressChanged
    '    RefreshRecordCount()
    'End Sub
#End Region

#Region "User Control Events"

    Private Sub uc_OKButtonClicked(ByVal sender As Object, ByVal e As RoutedEventArgs) _
        Handles UcNewUser.OkButtonClicked
        UcNewUser.busyAnimationNewUser_visibility = Windows.Visibility.Visible
        _backgroundWorker_CheckUser = New BackgroundWorker
        _backgroundWorker_CheckUser.RunWorkerAsync(UcNewUser.TextBoxNewUser.Text)
        _backgroundWorker_CheckUser.Dispose()
    End Sub

    Private Sub uc_CancelButtonClicked(ByVal sender As Object, ByVal e As RoutedEventArgs) _
        Handles UcNewUser.CancelButtonClicked
        MyCanvas.Visibility = Windows.Visibility.Collapsed
    End Sub

#End Region

    '#Region "New Item Canvas"


    '    Private m_StartPoint As Point ' Where did the mouse start off from?
    '    Private m_OriginalLeft As Double ' What was the element's original x offset?
    '    Private m_OriginalTop As Double ' What was the element's original y offset?
    '    Private m_IsDown As Boolean ' Is the mouse down right now?
    '    Private m_IsDragging As Boolean ' Are we actually dragging the shape around?
    '    Private m_OriginalElement As UIElement ' What is it that we're dragging?
    '    Private m_OverlayElement As Rectangle ' What is it that we're using to show where the shape will end up?


    '    Private Sub MyCanvas_PreviewMouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles MyCanvas.PreviewMouseLeftButtonDown


    '        If MyCanvas Is e.Source Then
    '            Exit Sub
    '        End If

    '        m_IsDown = True
    '        m_StartPoint = e.GetPosition(MyCanvas)
    '        m_OriginalElement = e.Source
    '        MyCanvas.CaptureMouse()

    '        e.Handled = True


    '        'm_IsDragging = False

    '        'dim
    '        ''get the mouse position, and set it to only be picked up
    '        ''when it is in the top part of the canvas.
    '        'Me.origCursorLocation = e.GetPosition(Me)
    '        ''see what element was clicked
    '        'm_OriginalElement = MyCanvas.FindCanvasChild(TryCast(e.Source, DependencyObject))
    '        'If Me.ElementBeingDragged Is Nothing Then
    '        '    Return
    '        'End If


    '        ''*************************************************************
    '        ''* Let the user click only on the top of the canvas to move it!
    '        ''
    '        ''************************************************************

    '        'Dim pMouseLocation As New Point(e.GetPosition(Me.elementBeingDragged).X, e.GetPosition(Me.elementBeingDragged).Y)
    '        ''The range of where my window runs, furthest both x and y

    '        'Dim pWindowBar As New Point(Me.elementBeingDragged.DesiredSize.Width, 25)
    '        ''Get the difference and then store that

    '        'Dim pDifference As New Point((pWindowBar.X - pMouseLocation.X), (pWindowBar.Y - pMouseLocation.Y))
    '        ''If the difference of the cursor and their mouse isn't out of the range, then let them move the window, if it is let them access the other stuff in the canvas
    '        'If pDifference.X > 0 AndAlso pDifference.Y > 0 Then
    '        '    'Let them drag because they are in the top of the window!!

    '        '    ' Cache the mouse cursor location.
    '        '    Me.origCursorLocation = e.GetPosition(Me)

    '        '    ' Walk up the visual tree from the element that was clicked,
    '        '    ' looking for an element that is a direct child of the Canvas.
    '        '    Me.ElementBeingDragged = Me.FindCanvasChild(TryCast(e.Source, DependencyObject))
    '        '    If Me.ElementBeingDragged Is Nothing Then
    '        '        Return
    '        '    End If

    '        '    ' Get the element's offsets from the four sides of the Canvas.
    '        '    Dim left As Double = Canvas.GetLeft(Me.ElementBeingDragged)
    '        '    Dim right As Double = Canvas.GetRight(Me.ElementBeingDragged)
    '        '    Dim top As Double = Canvas.GetTop(Me.ElementBeingDragged)
    '        '    Dim bottom As Double = Canvas.GetBottom(Me.ElementBeingDragged)

    '        '    ' Calculate the offset deltas and determine for which sides
    '        '    ' of the Canvas to adjust the offsets.
    '        '    Me.origHorizOffset = ResolveOffset(left, right, Me.modifyLeftOffset)
    '        '    Me.origVertOffset = ResolveOffset(top, bottom, Me.modifyTopOffset)

    '        '    ' Set the Handled flag so that a control being dragged
    '        '    ' does not react to the mouse input.
    '        '    e.Handled = True


    '        '    'MessageBox.Show("Mouse Location: " + e.GetPosition(this.elementBeingDragged) + "\n"
    '        '    '+ "Element: " + this.elementBeingDragged.ToString() + "\n"
    '        '    '+ "Element Location: " + Canvas.GetLeft(this.elementBeingDragged) + "," + Canvas.GetTop(this.elementBeingDragged)
    '        '    ');
    '        '    '

    '        '    Me.isDragInProgress = True
    '        'Else
    '        '    ' Set the Handled flag so that a control being dragged
    '        '    ' does not react to the mouse input.
    '        '    e.Handled = False
    '        '    Me.elementBeingDragged.ReleaseMouseCapture()
    '        '    Me.isDragInProgress = False
    '        'End If


    '    End Sub

    '    Private Sub MyCanvas_PreviewMouseMove(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles MyCanvas.PreviewMouseMove
    '        If m_IsDown Then
    '            If Not m_IsDragging AndAlso _
    '             Math.Abs(e.GetPosition(MyCanvas).X - m_StartPoint.X) > SystemParameters.MinimumHorizontalDragDistance AndAlso _
    '             Math.Abs(e.GetPosition(MyCanvas).Y - m_StartPoint.Y) > SystemParameters.MinimumVerticalDragDistance Then
    '                DragStarted()
    '            End If
    '            If m_IsDragging Then
    '                DragMoved()
    '            End If
    '        End If
    '    End Sub

    '    Private Sub DragStarted()
    '        m_IsDragging = True

    '        m_OriginalLeft = Canvas.GetLeft(m_OriginalElement)
    '        m_OriginalTop = Canvas.GetTop(m_OriginalElement)

    '        ' Add a rectangle to indicate where we'll end up.
    '        ' We'll just use an alpha-blended visual brush.
    '        Dim brush As VisualBrush
    '        brush = New VisualBrush(m_OriginalElement)
    '        brush.Opacity = 0.5

    '        m_OverlayElement = New Rectangle()
    '        m_OverlayElement.Width = m_OriginalElement.RenderSize.Width
    '        m_OverlayElement.Height = m_OriginalElement.RenderSize.Height
    '        m_OverlayElement.Fill = brush

    '        MyCanvas.Children.Add(m_OverlayElement)
    '    End Sub

    '    Private Sub DragMoved()
    '        Dim currentPosition As Point = System.Windows.Input.Mouse.GetPosition(MyCanvas)
    '        Dim elementLeft As Double = (currentPosition.X - m_StartPoint.X) + m_OriginalLeft
    '        Dim elementTop As Double = (currentPosition.Y - m_StartPoint.Y) + m_OriginalTop
    '        Canvas.SetLeft(m_OverlayElement, elementLeft)
    '        Canvas.SetTop(m_OverlayElement, elementTop)
    '    End Sub

    '    Private Sub MyCanvas_PreviewMouseLeftButtonUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles MyCanvas.PreviewMouseLeftButtonUp
    '        If m_IsDown Then
    '            DragFinished(False)
    '            e.Handled = True
    '        End If
    '    End Sub

    '    Private Sub Window1_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Me.PreviewKeyDown
    '        ' This is handled at the window level, because neither MyCanvas nor
    '        ' its children ever get keyboard focus.
    '        If e.Key = Input.Key.Escape AndAlso m_IsDragging Then
    '            DragFinished(True)
    '        End If
    '    End Sub

    '    Private Sub DragFinished(ByVal canceled As Boolean)
    '        System.Windows.Input.Mouse.Capture(Nothing)
    '        If m_IsDragging Then
    '            MyCanvas.Children.Remove(m_OverlayElement)
    '            If Not canceled Then
    '                Canvas.SetLeft(m_OriginalElement, Canvas.GetLeft(m_OverlayElement))
    '                Canvas.SetTop(m_OriginalElement, Canvas.GetTop(m_OverlayElement))
    '            End If
    '            m_OverlayElement = Nothing
    '        End If
    '        m_IsDragging = False
    '        m_IsDown = False
    '    End Sub
    '#End Region


End Class

#Region "Converters"

Public Class ImageConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object _
        Implements IValueConverter.Convert
        If value IsNot Nothing Then
            Dim _userTable As UserTable = DirectCast(value, UserTable)
            Dim isLocked As Boolean = _userTable.AccountLocked
            Dim _
                imageLocation As String = _
                    If(isLocked, "../../images/administration/lock.png", "../../images/administration/lock_unlock.png")
            Return (imageLocation)
        End If

        Return String.Empty
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) _
        As Object Implements IValueConverter.ConvertBack
        Throw New Exception("The method or operation is not implemented.")
    End Function
End Class



#End Region

